<template>
  <el-container>
    <el-row class="nav">
      <span class="font-weight">{{$store.state.orderTypeName}}</span>
    </el-row>
    <el-divider></el-divider>
    <el-header style="display:flex;width:100%">
      <el-col :span='10'
              style="white-space:nowrap;">
        <div class="block">
          <span class="demonstration">时间：</span>
          <el-date-picker v-model="timerValue"
                          size="mini"
                          clearable
                          type="daterange"
                          align="left"
                          value-format="yyyy-MM-dd"
                          unlink-panels
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          :picker-options="pickerOptions">
          </el-date-picker>
        </div>
      </el-col>
      <el-col :span='14'>
        <el-row>
          <el-col :span='16'
                  style="display:flex;align-items: center;padding-right:20px;"
                  v-if="$store.state.dataShowTypeTitleId == 1">
            <span class="per-item-txt">工单流程：</span>
            <el-select clearable
                       size="mini"
                       v-model="orderType"
                       placeholder="请选择">
              <el-option v-for="item in type"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          <!-- <el-col :span='8'
                  v-if="$store.state.dataShowTypeTitleId == 1"
                  style="display:flex;align-items: center;">
            <span class="per-item-txt">来源：</span>
            <el-select clearable
                       size="mini"
                       v-model="source"
                       placeholder="请选择">
              <el-option v-for="item in sourceList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col> -->
          <el-col :span='16'
                  v-if="$store.state.dataShowTypeTitleId == 2"
                  style="display:flex;align-items: center;">
            <el-button size="mini"
                       class="h30Btn"
                       :class= "btnType == 'user'?'el-button--primary':''"
                       @click="selectData('user')">按用户查看</el-button>
            <el-button size="mini"
                       class="h30Btn"
                       :class= "btnType == 'beifen'?'el-button--primary':''"
                       @click="selectData('beifen')">按部门查看</el-button>
          </el-col>
          <el-col :span='8'
                  class='btn-havior'>
            <el-button size="mini"
                       class="el-button el-button--primary el-button--medium h30Btn"
                       @click="exportList">导出</el-button>
            <el-button size="mini"
                       @click="selectData"
                       class="el-button el-button--primary el-button--medium h30Btn"
                       v-if="$store.state.dataShowTypeTitleId == 1">查询</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-header>
    <el-row :gutter='50'
            class='table-pic-data'>
      <el-col :span='6'
              class='per-table-pic-data'
              v-for='(item,index) in tablePicData'
              :key='index'>
        <div @click="echartChange(item)"
             :class="{'item_con':item.isClicked,'line_show ':item.checked}">
          <div>{{item.text}}</div>
          <div>{{item.num}}</div>
          <div class="active"></div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-tabs type="border-card">
        <el-tab-pane label="图表">
          <div id="echart-data-pic"
               ref="myEchart"></div>
        </el-tab-pane>
        <el-tab-pane label="列表">
          <el-table :data="tableData3"
                    stripe
                    border
                    tooltip-effect="dark"
                    :header-cell-style="{background:'#F2F3F8'}"
                    fixed>
            <el-table-column prop="time"
                             label="日期">
            </el-table-column>
            <el-table-column prop="createCount"
                             label="创建工单数">
            </el-table-column>
            <el-table-column prop="complateCount"
                             label="完成工单数">
            </el-table-column>
            <el-table-column prop="timeOutCount"
                             label="超时工单数">
            </el-table-column>
            <el-table-column prop="timeOutComplatedCount"
                             label="超时完成数">
            </el-table-column>
            <el-table-column prop="finishRate"
                             label="总体完成率">
              <template slot-scope="scope">
                {{scope.row.finishRate ? scope.row.finishRate.toFixed(2)+'%':0}}
              </template>
            </el-table-column>
            <el-table-column prop="averageFinishTime"
                             label="平均完成时长">
            </el-table-column>
          </el-table>
          <el-row>
            <el-pagination background
                           class="el-pagination-style"
                           :current-page="page"
                           :page-sizes="[10, 20, 50, 100]"
                           :page-size="pageSize"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="totalDataLength">
            </el-pagination>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </el-container>
</template>

<script>
import echarts from 'echarts'
import { getAllSelectFieldListById } from "@/api/customField"
import { getWorkOrderTypeByUserId } from "@/api/workOrderController";
import { reportdata, getDetailList, getGraphicsDate } from '@/api/dataAnalysis'
import { selectUser } from '@/api/userController'
import { detailListForExcel, getCreaterList } from '@/api/reportDataController'
export default {
  data () {
    return {
      btnType:'user',
      xList: [],
      yList: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      routerId: 1,
      orderType: '',
      type: [],
      timerValue: "",
      source: '',
      // sourceList: [],
      charts: '',
      totalDataLength: 0,
      page: 1,
      pageSize: 10,
      tablePicDataList: {},
      tablePicData: [
        {
          text: '创建工单数',
          num: 0,
          name: 'createCount',
          isClicked: true,
          checked: false,
          isStartClick: false
        },
        {
          text: '完成工单数',
          num: 0,
          name: 'complateCount',
          isClicked: true,
          checked: false
        },
        {
          text: '总体完成率',
          num: 0,
          name: 'finishRate',
          percent: true
        },
        {
          text: '工单平均完成时长',
          num: 0,
          name: 'averageFinishTime'
        },
        {
          text: '超时工单总数',
          num: 0,
          name: 'timeOutCount',
          isClicked: true,
          checked: false
        },
        {
          text: '超时完成数',
          num: 0,
          name: 'timeOutComplatedCount',
          isClicked: true,
          checked: false
        },
        {
          text: '转入工单数',
          num: 0,
          name: '11',
          // isClicked: true,
          // checked: false
        },
        {
          text: '转出工单数',
          num: 0,
          name: '22',
          // isClicked: true,
          // checked: false
        }
      ],
      tableData3: []
    }
  },
  components: {

  },
  watch: {
    $route (to, from) {
      this.timerValue = ''
      this.orderType = ''
      this.source = ''
      let urlRoutes = to.path
      urlRoutes = urlRoutes.split('/')
      this.routerId = urlRoutes[2]
      this.selectData('user');
      // this.$store.commit('orderTypeIdFun', this.urlRoute)
    }
  },
  create () {
  },
  mounted () {
    //  将回调函数延迟在下一次dom更新数据后调用,当数据更新了，在dom中渲染后，自动执行该函数，
    this.$nextTick(function () {
      this.myEchartData()
    })
    this.getDepartmentId()
    this.getWorkOrderTypeByUserIdFun()
    // this.getAllSelectFieldListByIdFun(4)
    this.selectData('user')
    
  },
  beforeDestroy () {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    getDepartmentId () {
      let _this = this 
      selectUser(_this.$store.state.userId).then(res => {
        let data = res.data
        if (data.retCode == 200) {
          _this.departmentId = data.data.departmentId
        }
      })
    },
    echartChange (e) {
      if (e.isClicked) {
        this.tablePicData.forEach((item, index) => {
          this.tablePicData[index].checked = false
        })
        e.checked = true
        let name = e.name + 'List'
        this.yList = this.tablePicDataList[name]
        this.xList = this.tablePicDataList.xaxisList
        this.chartTitle = e.text
        this.myEchartData()
      }
    },
    // getAllSelectFieldListByIdFun (id) {
    //   // 本地数据
    //   getAllSelectFieldListById(id).then(res => {
    //     let data = res.data;
    //     if (data.retCode === 200) {
    //       let dataInfo = data.data
    //       if (id === 3) {
    //         this.priority = dataInfo
    //       } else if (id === 4) {
    //         this.sourceList = dataInfo
    //       }
    //     }
    //   });
    // },
    // 获取工单流程
    getWorkOrderTypeByUserIdFun () {
      let id = this.$store.state.userId
      getWorkOrderTypeByUserId(id).then(res => {
        let data = res.data;
        if (data.retCode === 200) {
          this.type = data.data;
        }
      });
    },
    myEchartData () {
      this.chart = echarts.init(this.$refs.myEchart)
      // selectAll().then(res => { // 调取接口获取数据处
      this.chart.setOption({
        title: {
          text: this.chartTitle
        },

        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          // data: this.xList.map(function (item) {
          //   return item[0]
          // })
          boundaryGap: false,
          data: this.xList
        },
        yAxis: {
          splitLine: {
            show: false
          }
        },
        toolbox: {
          left: 'center',
          top: 20,
          feature: {
            dataZoom: {
              show: false,
            },
            restore: {
              emphasis: {
                iconStyle: {
                  textPosition: 'top'
                }
              }
            },
            saveAsImage: {
              iconStyle: {

              },
              emphasis: {
                iconStyle: {
                  textPosition: 'top'
                }
              }
            }
          }
        },
        dataZoom: [{
          startValue: '2014-06-01'
        }, {
          type: 'inside'
        }],
        visualMap: {
          top: 10,
          right: 10,
          pieces: [{
            gt: 0,
            lte: 50,
            color: '#096'
          }, {
            gt: 50,
            lte: 100,
            color: '#ffde33'
          }, {
            gt: 100,
            lte: 150,
            color: '#ff9933'
          }, {
            gt: 150,
            lte: 200,
            color: '#cc0033'
          }, {
            gt: 200,
            lte: 300,
            color: '#660099'
          }, {
            gt: 300,
            color: '#7e0023'
          }],
          outOfRange: {
            color: '#999'
          }
        },
        series: {
          name: '数据详情',
          type: 'line',
          data: this.yList,
          // data: data.map(function (item) {
          //   return item[1]
          // }),
          // markLine: {
          //   silent: true,
          //   data: [{
          //     yAxis: 50
          //   }, {
          //     yAxis: 100
          //   }, {
          //     yAxis: 150
          //   }, {
          //     yAxis: 200
          //   }, {
          //     yAxis: 300
          //   }]
          // }
        }
      })
      // })
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize;
      this.page = 1;
      this.selectData(this.btnType);
    },
    handleCurrentChange (page) {
      this.page = page;
      this.selectData(this.btnType);
    },
    getGraphicsDateFun (dt) {
      let params;
      let _this = this
      if (this.routerId == 1) {
        params = {
          startTime: this.timerValue && this.timerValue.length > 0 ? this.timerValue[0] : '',
          endTime: this.timerValue && this.timerValue.length > 0 ? this.timerValue[1] : '',
          workOrderTypeId: this.orderType,
          source: this.source
        }
      } else {
        params = {
          startTime: this.timerValue && this.timerValue.length > 0 ? this.timerValue[0] : '',
          endTime: this.timerValue && this.timerValue.length > 0 ? this.timerValue[1] : '',
          userId: this.$store.state.userId
        }
      }
      if (dt == 'beifen') {
        params.departmentId = this.departmentId || ''
      }
      getGraphicsDate(params).then(res => {
        let data = res.data;
        if (data.retCode === 200 && data.data) {
          // _this.tablePicDataList.complateCountList = data.data.complateCountList && data.data.complateCountList.reverse()
          // _this.tablePicDataList.createCountList = data.data.createCountList && data.data.createCountList.reverse()
          // _this.tablePicDataList.timeOutComplatedCountList = data.data.timeOutComplatedCountList && data.data.timeOutComplatedCountList.reverse()
          // _this.tablePicDataList.timeOutCountList = data.data.timeOutCountList && data.data.timeOutCountList.reverse()
          // _this.tablePicDataList.xaxisList = data.data.xaxisList && data.data.xaxisList.reverse()
          _this.tablePicDataList = data.data
          _this.echartChange(_this.tablePicData[0])
        }
      })
    },
    // 查询
    selectData (dt) {
      this.btnType = dt
      let params;
      if (this.routerId == 1) {
        params = {
          startTime: this.timerValue && this.timerValue.length > 0 ? this.timerValue[0] : '',
          endTime: this.timerValue && this.timerValue.length > 0 ? this.timerValue[1] : '',
          workOrderTypeId: this.orderType,
          source: this.source
        }
      } else {
        params = {
          startTime: this.timerValue && this.timerValue.length > 0 ? this.timerValue[0] : '',
          endTime: this.timerValue && this.timerValue.length > 0 ? this.timerValue[1] : '',
          userId: this.$store.state.userId
        }
      }
      if (dt == 'beifen') {
        params.departmentId = this.departmentId
        this.getGraphicsDateFun(dt)
      } else {
        this.getGraphicsDateFun()
      }
      // 查询头部及列表数据
      reportdata(params).then(res => {
        let data = res.data;
        if (data.retCode === 200) {
          this.tablePicData.forEach((item, index) => {
            if (data.data[item.name]) {
              let str = ''
              str = data.data[item.name]
              if (item.percent) {
                str = str.toFixed(2)
                str += '%'
              }
              this.tablePicData[index].num = str
            } else if (data.data[item.name] == 0) {
              this.tablePicData[index].num = 0
            }
          })
        }
      })
      params.page = this.page
      params.pageSize = this.pageSize
      getDetailList(params).then(res => {
        let data = res.data;
        if (data.retCode === 200) {
          this.tableData3 = data.data
          this.totalDataLength = data.count
        }
      })
      this.getGraphicsDateFun()
    },
    // 文件转换
    transBlob (data) {
      const blob = new Blob([data]);//new Blob([res])中不加data就会返回下图中[objece objece]内容（少取一层）
      const fileName = '导出文件.xlsx';//下载文件名称
      const elink = document.createElement('a');
      elink.download = fileName;
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    },
    // 导出
    exportList () {
      var params = {
        "endTime": this.timerValue[1] || '',
        "source": this.source || '',
        "startTime": this.timerValue[0] || '',
        "tenantId": sessionStorage.getItem('tenantId') || window.CONFIG.tenantId,
        "userId": this.$store.state.userId,
        "departmentId": this.departmentId || '',
        "workOrderTypeId": this.orderType + '' || ''
      }
      if (this.$store.state.dataShowTypeTitleId === 1) {
        params.userId = ""
        params.departmentId = ""
        detailListForExcel(params).then(res => {
          this.transBlob(res.data)
        })
      } else if (this.$store.state.dataShowTypeTitleId === 2) {
        params.source = ''
        params.workOrderTypeId = ''
        getCreaterList(params).then(res => {
          this.transBlob(res.data)
        })
      }
    }
  }
}
</script>

<style  scoped>
.per-item-txt {
  white-space: nowrap;
}
.btn-havior >>> .el-button {
  float: right;
}
#echart-data-pic {
  /* width: 100%; */
  min-height: 400px;
}
#echart-data-pic:first-child {
  width: 100%;
}
.echart_header {
  line-height: 40px;
}
.table-pic-data {
  margin-right: 0 !important;
  margin-left: 0 !important;
  margin-bottom: 10px;
  padding: 20px;
  background: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
}
.per-table-pic-data div {
  line-height: 40px;
}
.per-table-pic-data {
  padding: 15px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}
.item_con {
  cursor: pointer;
}
>>> .el-tabs__nav {
  float: right;
}
.active {
  width: 60%;
  height: 5px;
  background-color: #9b9ba0;
}
.line_show {
  font-weight: 600;
  color: #4786c3;
  cursor: pointer;
}
.line_show .active {
  background-color: #4786c3;
}
>>> .el-header {
  padding: 0;
}
>>> .el-button + .el-button {
  margin-left: 0;
  margin-right: 10px;
}
>>> .el-pagination {
  padding: 10px 5px;
  text-align: right;
}
</style>
